package com.holyn.guofang.view.distinguish;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.BrandItemInfoWo;
import com.holyn.guofang.model.webhttp.wo.GraphTransWo;
import com.holyn.guofang.model.webhttp.wo.ImageWo;
import com.holyn.guofang.model.webhttp.wo.StatusWo;
import com.holyn.guofang.model.webhttp.wo.TaskIDWo;
import com.holyn.guofang.model.webhttp.wo.UserCardListWo;
import com.holyn.guofang.model.webhttp.wo.UserInfoWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.distinguish.DistinguishContract;
import com.holyn.guofang.presenter.distinguish.DistinguishPresenter;
import com.holyn.guofang.utils.MD5Uitl;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.viewcommon.crop.CropActivity;
import com.holyn.guofang.viewcommon.dialog.TaskPayDialog;
import com.holyn.guofang.viewcommon.dialog.ToastDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

/**
 * Created by Holyn on 2017/6/13.
 * 1、2.3.8获取注册信息，判断卡是否过期
 * 2、卡已过期，2.5.6 获取用户的国方卡信息,请求后只做提示
 * 3、卡未过期， 商标源图ID为空时或主图换了，调用 2.4.2上传图片获取商标源图ID。如果源图不为空执行2.4.1获取任务id
 * 4、接着，三十秒前逻辑  2.4.12（执行商标识别任务） ，如果30秒无数据返回，则中断改请求，执行2.4.13（请求获取商标查询结果getSearchResultByTaskID）
 * 5、查询成功后，根据2.4.1获取的任务id，进行扣费规则
 * 6、蛋疼的逻辑
 *
 *
 * 逻辑修改为如下（2018-09-29）：
 * 1、每次选择完或者剪切完成照片，就自动上传图片（调用 2.4.2），获取商标源图ID
 * 2、成功上传图片后调用图转文的接口（2.4.19 ），获取并显示信息
 * 3、点击识别查询，调用2.3.8获取注册信息，判断卡是否过期
 * 4、卡已过期，2.5.6 获取用户的国方卡信息,请求后只做提示
 * 5、卡未过期， 执行2.4.1获取任务id
 * 6、接着，三十秒前逻辑  2.4.12（执行商标识别任务） ，如果30秒无数据返回，则中断改请求，执行2.4.13（请求获取商标查询结果getSearchResultByTaskID）
 * 7、查询成功后，根据2.4.1获取的任务id，进行扣费规则
 * 8、蛋疼的逻辑+
 *
 */

public class CommonDistinguishActivity extends BaseActivity implements BaseView, DistinguishContract.CommonView, DistinguishContract.ResposeGraphTransListener{
    private static final int REQUEST_ACTION_POST_TASK_ID = 0x0001;
    private static final int REQUEST_ACTION_UPLOAD_IMAGE = 0x0002;
    private static final int REQUEST_ACTION_POST_BRAND_DISTINGUISH = 0x0003;
    private static final int REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID = 0x0004;
    private static final int REQUEST_ACTION_POST_GRAP_TRANS = 0x0005;//图转文

    /**
     * 2.3.8 判断返回参数 userCard ,如果该字段 内容为空，代表卡已过期，非空则代表未过期
     */
    private static final int REQUEST_ACTION_POST_USER_INFO = 0x0006;
    /**
     * 卡已过期
     * 2.5.6 获取用户的国方卡信息,请求后只做提示
     * 1.1.1—>如果 个数 大于 0 则 ，提示  当前国方卡已过期，请前往 我的-用卡管理 激活卡。
     * 1.1.2—>如果等于0，则提示  当前国方卡已过期，请前往 我的-购国方卡 购卡。
     */
    private static final int REQUEST_ACTION_POST_USER_CARD_LIST = 0x0007;
    /**
     * 卡未过期，根据2.3.8 返回的validMethod进行判断
     * 1.1->当validMethod=0 时，弹出界面，输入的密码需要md5加密。注意这个密码是在激活卡时（我的-用卡管理），当用户选择密码验证 时，需要弹框让用户设定密码，并非登录密码。
     * 1.2->当validMethod=1 时，弹出界面，点获取验证码按钮 对应接口 2.4.17 获取任务支付验证码
     * 1.3->当validMethod=2时，空值，这个就不用弹界面了，直接调用2.4.18接口。
     */
    private static final int REQUEST_ACTION_POST_TASK_PAY_CODE = 0x0008;//2.4.17
    private static final int REQUEST_ACTION_POST_TASK_PAY = 0x0009;//2.4.18

    public static final String INTENT_ACTION_KEY = "intent_action_key";
    public static final int INTENT_ACTION_VALUE_OPEN_ALBUM = 1;
    public static final int INTENT_ACTION_VALUE_TAKE_PHOTO = 2;

    public static final int REQUEST_CODE_CROP_IMAGE = 0x0003;
    public static final int REQUEST_CODE_GET_CLASSFIY_CODE = 0x0004;
    public static final int REQUEST_CODE_GO_SENIOR_DISTINGGUISH = 0x0005;
    public static final int REQUEST_CODE_IMAGE_ELEMENT = 0x0006;//图形要素编码选择

    public static final String INTENT_KEY_IMAGE_PATH = "INTENT_IMAGE_PATH";

    @BindView(R.id.imageview)
    ImageView imageview;
    @BindView(R.id.tv_album)
    TextView tvAlbum;
    @BindView(R.id.tv_take_photo)
    TextView tvTakePhoto;
    @BindView(R.id.tv_crop)
    TextView tvCrop;
    @BindView(R.id.cb_auto_img_to_word)
    CheckBox cbAutoImgToWord;
    @BindView(R.id.cb_auto_img_to_img_basic)
    CheckBox cbAutoImgToImgBasic;
    @BindView(R.id.btn_edit)
    Button btnEdit;
    @BindView(R.id.ll_search_content)
    LinearLayout llSearchContent;
    @BindView(R.id.et_key_cn)
    EditText etKeyCn;
    @BindView(R.id.et_key_en)
    EditText etKeyEn;
    @BindView(R.id.tv_select_img_element)
    TextView tvSelectImgElement;
    @BindView(R.id.tv_clear_img_element)
    TextView tvClearImgElement;
    @BindView(R.id.et_key_img)
    EditText etKeyImg;
    @BindView(R.id.tv_classfiy_select)
    TextView tvClassfiySelect;
    @BindView(R.id.tv_classfiy)
    TextView tvClassfiy;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    private int intentActionValue;

    private DistinguishContract.Presenter presenter;

    private List<LocalMedia> selectList = new ArrayList<>();
    private String imagePath = "";

    private String curSelectCodeType = "";
    private String curSelectCode = "";

    private MyCountDownTimer timer; //倒计时定时器

    private int pageSize = 20;

    private TaskPayDialog passwordTaskPayDialog = null;
    private TaskPayDialog validCodeTaskPayDialog = null;

    /**
     * 图转文接口参数
     */
    int isAutoImgToWord = 1;
    int isAutoImgToImgbasic = 0;

    /**
     * 执行商标识别
     * @param TaskID 任务 ID，由客户端请求前产生
     * @param FrontCount 首次返回前面记录数量
     * @param QueryMode 查询方式
     * @param SrcImgID 商标源图 ID(非图片流，若该值为空或空字符串， 则需要传一个图片流)
     * @param ImgIDs 其它图文件名，可以是多个，可空，多个时用“;” 分割
     * @param CnContent 商标的中文文字
     * @param EnContent 商标的英文文字
     * @param ImageCode 商标的图形要素图形要素编码
     * @param MarkClass 类别
     * @param MarkGroup 群组
     * @param ImageQueryMode 图像识别查询算法类型
     * @param ImageAlgorithm 图像识别的查询算法
     * @param CnQueryMode 中文查询算法类型
     * @param CnAlgorithm 中文的查询算法
     * @param EnQueryMode 西文查询算法类型
     * @param EnAlgorithm 英文的查询算法
     * @param CodeQueryMode 图形要素编码查询算法类型
     * @param CodeAlgorithm 图形要素编码的查询算法
     * @param State 状态过滤
     * @param DateType 过滤日期
     * @param BeginDate 过滤起始日期
     * @param EndDate 过滤截止日期
     */
    Integer TaskID;
    Integer FrontCount = pageSize;
    String QueryMode = "0";
    String SrcImgID = "";
    String ImgIDs = "";//其它图文件名，可以是多个，可空，多个时用“;” 分割;没子图是为空
    String CnContent = "";
    String EnContent = "";
    String ImageCode = "";
    String MarkClass = "";
    String MarkGroup = "";
    String ImageQueryMode = "0";
    String ImageAlgorithm = "";
    String CnQueryMode = "";
    String CnAlgorithm = "";
    String EnQueryMode = "";
    String EnAlgorithm = "";
    String CodeQueryMode = "";
    String CodeAlgorithm = "";
    String State = "0";
    String DateType = "0";
    String BeginDate = "";
    String EndDate = "";

    private String mainImageUrl = "";

    private UserInfoWo.UserInfoBean.UserCardBean cardBean;

    private BrandItemInfoWo brandItemInfoWo;

    private String MarkClassOnlyPostGraph= "" ;// 商标的图形要素图形要素编码, 只用于调用GraphTranslation.ahsx
    private boolean isClickImgToSelectMarkClass = false; //是否点击了图像CheckBox，然后去选择一个商品类型（商品服务范围）

    public static void start(Activity fromActivity, String imagePath) {
        Intent intent = new Intent(fromActivity, CommonDistinguishActivity.class);
        intent.putExtra(INTENT_KEY_IMAGE_PATH, imagePath);
        fromActivity.startActivity(intent);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_common_distinguish;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
//        showToolbarMenuRight("普通识别查询", true, "高级识别", new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                SeniorDistinguishActivity.startForResult(CommonDistinguishActivity.this, imagePath, SrcImgID, mainImageUrl, REQUEST_CODE_GO_SENIOR_DISTINGGUISH);
//            }
//        });
//        取消高级识别
        showToolbar("高级识别查询");

        imagePath = getIntent().getStringExtra(INTENT_KEY_IMAGE_PATH);
        Glide.with(CommonDistinguishActivity.this).load(imagePath)
//                .error(R.drawable.ic_empty_image)
                .into(imageview);

        presenter = new DistinguishPresenter(this);
        presenter.addCommonViewListener(this);

        presenter.addResposeGraphTransListener(this);//监听图转文回调

        if (TextUtils.isEmpty(SrcImgID)){
            presenter.uploadImage(REQUEST_ACTION_UPLOAD_IMAGE, imagePath);
        }

        cbAutoImgToWord.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    isAutoImgToWord = 1;
                } else {
                    isAutoImgToWord = 0;
                }
                if (!(isAutoImgToWord == 0 && isAutoImgToImgbasic == 0)){
                    presenter.postGraphTranslation(REQUEST_ACTION_POST_GRAP_TRANS, SrcImgID, isAutoImgToWord, isAutoImgToImgbasic, MarkClassOnlyPostGraph);
                }
            }
        });

        cbAutoImgToImgBasic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    isAutoImgToImgbasic = 1;
                    showClickImagToSelectClassDialog();
                } else {
                    isAutoImgToImgbasic = 0;
                    if (isAutoImgToWord == 1){
                        presenter.postGraphTranslation(REQUEST_ACTION_POST_GRAP_TRANS, SrcImgID, isAutoImgToWord, isAutoImgToImgbasic, MarkClassOnlyPostGraph);
                    }
                }

            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
//                case PictureConfig.CHOOSE_REQUEST:
//                    // 图片选择结果回调
//                    selectList = PictureSelector.obtainMultipleResult(data);
//                    // 例如 LocalMedia 里面返回三种path
//                    // 1.media.getPath(); 为原图path
//                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
//                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
//                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
//                    LogUtils.d(selectList.get(0));
//                    imagePath = selectList.get(0).getCompressPath();
//                    Glide.with(CommonDistinguishActivity.this).load(imagePath)
////                            .error(R.drawable.ic_empty_image)
//                            .into(imageview);
//
//                    SrcImgID = "";//重新选择图片之后，图片需要重新上传
//                    mainImageUrl = "";
//
//                    presenter.uploadImage(REQUEST_ACTION_UPLOAD_IMAGE, imagePath);
//                    break;
                case PictureConfirmActivity.REQUEST_CODE_OPEN_ALBUM:
                case PictureConfirmActivity.REQUEST_CODE_TAKE_PHOTO:
                    imagePath = data.getStringExtra(PictureConfirmActivity.INTENT_KEY_IMAGE_PATH);
                    Glide.with(CommonDistinguishActivity.this).load(imagePath)
//                            .error(R.drawable.ic_empty_image)
                            .into(imageview);

                    SrcImgID = "";//重新选择图片之后，图片需要重新上传
                    mainImageUrl = "";

                    presenter.uploadImage(REQUEST_ACTION_UPLOAD_IMAGE, imagePath);
                    break;
                case REQUEST_CODE_CROP_IMAGE:
                    imagePath = data.getStringExtra(CropActivity.EXTRA_RESULT_CROP_PATH);
                    LogUtils.d(imagePath);
                    Glide.with(CommonDistinguishActivity.this).load(imagePath)
//                            .error(R.drawable.ic_empty_image)
                            .into(imageview);

                    SrcImgID = "";//重新拍照选择图片之后，图片需要重新上传
                    mainImageUrl = "";

                    presenter.uploadImage(REQUEST_ACTION_UPLOAD_IMAGE, imagePath);
                    break;
                case REQUEST_CODE_GET_CLASSFIY_CODE:
                    curSelectCodeType = data.getStringExtra(ProductClassfiyActivity.INTENT_KEY_SELECT_CODE_TYPE);
                    curSelectCode = data.getStringExtra(ProductClassfiyActivity.INTENT_KEY_SELECT_CODE);
                    if (isClickImgToSelectMarkClass) {
                        if (curSelectCodeType.equals(ProductClassfiyActivity.TYPE_TYPE_CODE)){
                            if (curSelectCodeType.equals("全类")){
                                MarkClassOnlyPostGraph = "";
                            } else {
                                MarkClassOnlyPostGraph = curSelectCode;
                            }
                            MarkGroup = "";
                        } else {
                            MarkGroup = curSelectCode;
                            MarkClassOnlyPostGraph = "";
                        }

                        isClickImgToSelectMarkClass = false;

                        if (isAutoImgToWord == 1){
                            if (TextUtils.isEmpty(MarkClassOnlyPostGraph) || MarkClassOnlyPostGraph.contains(";")){
                                showClickImagToSelectClassDialog();
                            } else {
                                presenter.postGraphTranslation(REQUEST_ACTION_POST_GRAP_TRANS, SrcImgID, isAutoImgToWord, isAutoImgToImgbasic, MarkClassOnlyPostGraph);
                            }
                        }

                    } else {
                        if (curSelectCodeType.equals(ProductClassfiyActivity.TYPE_TYPE_CODE)){
                            if (curSelectCodeType.equals("全类")){
                                MarkClass = "";
                            } else {
                                MarkClass = curSelectCode;
                            }
                            MarkGroup = "";
                        } else {
                            MarkGroup = curSelectCode;
                            MarkClass = "";
                        }
                        tvClassfiy.setText("商品服务范围："+curSelectCode);

                    }

                    break;
                case REQUEST_CODE_IMAGE_ELEMENT:
                    ImageCode = data.getStringExtra(ImageElementActivity.INTENT_KEY_IMAGE_CODES);
                    etKeyImg.setText(ImageCode);
                    break;
            }
        }
    }

    @OnClick({R.id.tv_album, R.id.tv_take_photo, R.id.tv_crop, R.id.btn_edit, R.id.tv_select_img_element, R.id.tv_clear_img_element, R.id.tv_classfiy_select, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_album:
//                openAlbum();
                PictureConfirmActivity.startForResult(CommonDistinguishActivity.this, PictureConfirmActivity.REQUEST_CODE_OPEN_ALBUM);
                break;
            case R.id.tv_take_photo:
//                new RxPermissions(CommonDistinguishActivity.this)
//                        .request(Manifest.permission.WRITE_EXTERNAL_STORAGE
//                                , Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
//                        .subscribe(new Consumer<Boolean>() {
//                            @Override
//                            public void accept(@NonNull Boolean aBoolean) throws Exception {
//                                takePhoto();
//                            }
//                        });
                PictureConfirmActivity.startForResult(CommonDistinguishActivity.this, PictureConfirmActivity.REQUEST_CODE_TAKE_PHOTO);
                break;
            case R.id.tv_crop://该功能remove，20190119
                if (TextUtils.isEmpty(imagePath)){
                    toastMsg("请先选择图片");
                } else {
                    imageCrop();
                }
                break;
            case R.id.btn_edit:
                if (llSearchContent.isShown()){
                    btnEdit.setText("编辑");
                    llSearchContent.setVisibility(View.GONE);
                } else {
                    btnEdit.setText("隐藏");
                    llSearchContent.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.tv_select_img_element:
                ImageElementActivity.startForResult(CommonDistinguishActivity.this, REQUEST_CODE_IMAGE_ELEMENT);
                break;
            case R.id.tv_clear_img_element:
                etKeyImg.setText("");
                break;
            case R.id.tv_classfiy_select:
                ToastDialog toastDialog = new ToastDialog(CommonDistinguishActivity.this, true, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ProductClassfiyActivity.startForResult(CommonDistinguishActivity.this, REQUEST_CODE_GET_CLASSFIY_CODE);
                        dialog.dismiss();
                    }
                });
                toastDialog.setTvContent("商品范围数据将重置");
                toastDialog.show();
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(SrcImgID)){
                    toastMsg("图片上传失败，请重新选择");
                    return;
                }

                if (isAutoImgToImgbasic == 1 && (TextUtils.isEmpty(MarkClass) || MarkClass.contains(";"))){
                    showClickImagToSelectClassDialog();
                    return;
                }

                presenter.postUserInfo(REQUEST_ACTION_POST_USER_INFO);

//                if (TextUtils.isEmpty(SrcImgID)){
//                    presenter.uploadImage(REQUEST_ACTION_UPLOAD_IMAGE, imagePath);
//                } else {
//                    presenter.postTaskID(REQUEST_ACTION_POST_TASK_ID);
//                }

                break;
        }
    }

    private void openAlbum() {
        PictureSelector.create(CommonDistinguishActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .isCamera(false)
                .selectionMode(PictureConfig.SINGLE)
//                .compressGrade(Luban.FIRST_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                .compress(true)// 是否压缩
//                .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
//                        .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                        .compressMaxKB(100)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
//                        .compressWH(100, 100) // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    private void takePhoto() {
        PictureSelector.create(CommonDistinguishActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .imageFormat(".jpg")
//                .compressGrade(Luban.CUSTOM_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
//                .compressMaxKB(800)
                .compress(true)// 是否压缩
//                .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                .forResult(PictureConfig.CHOOSE_REQUEST);

        // 单独拍照
//        PictureSelector.create(CommonDistinguishActivity.this)
//                .openCamera(PictureMimeType.ofImage())// 单独拍照，也可录像 看你传入的类型是图片or视频
////                .theme(themeId)// 主题样式设置 具体参考 values/styles
//                .maxSelectNum(4)// 最大图片选择数量
//                .minSelectNum(1)// 最小选择数量
//                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
//                .previewImage(false)// 是否可预览图片
//                .previewVideo(false)// 是否可预览视频
//                .enablePreviewAudio(false)// 是否预览音频
//                .compressGrade(Luban.FIRST_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
//                .isCamera(false)// 是否显示拍照按钮
//                .compress(true)// 是否压缩
//                .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
//                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                .isGif(false)// 是否显示gif图片
//                .openClickSound(false)// 是否开启点击声音
////                .selectionMedia(selectList)// 是否传入已选图片
//                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
//                //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
//                //.compressWH() // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
//                //.videoQuality()// 视频录制质量 0 or 1
//                //.videoSecond()//显示多少秒以内的视频
//                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    private void imageCrop(){
        new RxPermissions(CommonDistinguishActivity.this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean){
                            Uri sourceUri = Uri.fromFile(new File(imagePath));
                            startActivityForResult(CropActivity.callingIntent(CommonDistinguishActivity.this, sourceUri), REQUEST_CODE_CROP_IMAGE);

                        }
                    }
                });
    }

    @Override
    public void requestStart(Integer requestAction) {
        LogUtils.d("requestStart....");
        showCountLoadingDialog();
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        LogUtils.d(e);
        if(requestAction == REQUEST_ACTION_POST_GRAP_TRANS){
            if (e instanceof SocketTimeoutException){
                toastMsg("图转文超时，请选择其它图片！");
            }
        }
        closeCountLoadingDialog();
    }

    @Override
    public void requestComplete(Integer requestAction) {
        LogUtils.d("requestComplete....");
    }

    @Override
    public void responseSuccess(int requestAction, UserInfoWo userInfoWo) {
        if (userInfoWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            cardBean = userInfoWo.getUserInfo().getUserCard();
            if (cardBean == null){//代表卡已过期
                presenter.postUserCardList(REQUEST_ACTION_POST_USER_CARD_LIST, 2, -1, -1);//请求后只做提示
            } else {//未过期
//                if (TextUtils.isEmpty(SrcImgID)){
//                    presenter.uploadImage(REQUEST_ACTION_UPLOAD_IMAGE, imagePath);
//                } else {
//                    presenter.postTaskID(REQUEST_ACTION_POST_TASK_ID);
//                }
                presenter.postTaskID(REQUEST_ACTION_POST_TASK_ID);
            }
        } else {
            closeCountLoadingDialog();
            toastMsg("获取用户详情失败");
        }

    }

    @Override
    public void responseSuccess(int requestAction, UserCardListWo userCardListWo) {
        if (userCardListWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            List<UserCardListWo.DataBean> dataBeanList = userCardListWo.getData();
            if (dataBeanList == null){
                toastMsg("当前国方卡已过期，请前往 我的-购国方卡 购卡");
            } else {
                if (dataBeanList.size() == 0){
                    toastMsg("当前国方卡已过期，请前往 我的-购国方卡 购卡");
                } else {
                    toastMsg("当前国方卡已过期，请前往 我的-用卡管理 激活卡");
                }
            }
        } else {
            toastMsg("获取获取用户的国方卡信息失败");
        }
        closeCountLoadingDialog();

    }

    @Override
    public void responseSuccess(Integer requestAction, TaskIDWo taskIDWo) {
        if (taskIDWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            TaskID = taskIDWo.getTaskID();
            CnContent = etKeyCn.getText().toString();
            EnContent = etKeyEn.getText().toString();
            ImageCode = etKeyImg.getText().toString();
            presenter.postBrandDistingush(REQUEST_ACTION_POST_BRAND_DISTINGUISH,
                    TaskID,
                    FrontCount,
                    QueryMode,
                    SrcImgID,
                    ImgIDs,
                    CnContent,
                    EnContent,
                    ImageCode,
                    MarkClass,
                    MarkGroup,
                    ImageQueryMode,
                    ImageAlgorithm,
                    CnQueryMode,
                    CnAlgorithm,
                    EnQueryMode,
                    EnAlgorithm,
                    CodeQueryMode,
                    CodeAlgorithm,
                    State,
                    DateType,
                    BeginDate,
                    EndDate);

            timer = new MyCountDownTimer();
            //timer.start();
        } else {
            closeCountLoadingDialog();
            toastMsg("获取任务ID失败");
        }
    }

    @Override
    public void responseSuccess(Integer requestAction, ImageWo imageWo) {
        if (imageWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            SrcImgID = imageWo.getSrcImgID();
            mainImageUrl = imageWo.getUrl();
//            presenter.postTaskID(REQUEST_ACTION_POST_TASK_ID);
            presenter.postGraphTranslation(REQUEST_ACTION_POST_GRAP_TRANS, SrcImgID, isAutoImgToWord, isAutoImgToImgbasic, MarkClassOnlyPostGraph);
        } else {
            closeCountLoadingDialog();
            toastMsg("上传图片失败:"+imageWo.getErr());
        }
    }

    @Override
    public void resposeGraphTrans(int requestAction, GraphTransWo graphTransWo) {
        if (graphTransWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            CnContent = graphTransWo.getData().getKeyWordCn();
            EnContent = graphTransWo.getData().getKeyWordEn();
            ImageCode = graphTransWo.getData().getImgBasic();

            etKeyCn.setText(CnContent);
            etKeyEn.setText(EnContent);
            etKeyImg.setText(ImageCode);
        } else {
            toastMsg("图转文失败，请稍后重试");
        }
        closeCountLoadingDialog();
    }

    @Override
    public void responseSuccess(Integer requestAction, BrandItemInfoWo brandItemInfoWo) {
        if (requestAction == REQUEST_ACTION_POST_BRAND_DISTINGUISH){
            //timer.cancel();
        }

        if (brandItemInfoWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            this.brandItemInfoWo = brandItemInfoWo;
            int validMethod = cardBean.getValidMethod();
            if (validMethod == 0){//弹出dialog，输入支付密码，再支付
                closeCountLoadingDialog();
                showPasswordTaskPayDialog();
            } else if (validMethod == 1){//弹出dialog，输入验证码，再支付
                closeCountLoadingDialog();
                showValidCodeTaskPayDialog();
            } else if (validMethod == 2){//直接支付
                presenter.postTaskPay(REQUEST_ACTION_POST_TASK_PAY, TaskID, "");
            }

        } else {
/******************************注释学习错误❌弹窗信息！**********************************************/
            //提示弹窗
//            final RxDialogSure rxDialogSure = new RxDialogSure(this);
//            rxDialogSure.getIvLogo().setImageResource(R.drawable.logo);
//            rxDialogSure.setTitle("❌错误❌");
//            rxDialogSure.setContent("status："+brandItemInfoWo.getStatus()+"\n"+"error：\n"+brandItemInfoWo.getErr()+"\n\n'brandItemInfoWo'："+brandItemInfoWo);
//            rxDialogSure.getTvSure().setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    rxDialogSure.cancel();
//                }
//            });
//            rxDialogSure.show();
/******************************注释学习错误❌弹窗信息！**********************************************/
            toastMsg("商标识别查询失败");
            closeCountLoadingDialog();
        }
    }

    @Override
    public void responseSuccess(int requestAction, StatusWo statusWo) {
        closeCountLoadingDialog();
        if (requestAction == REQUEST_ACTION_POST_TASK_PAY_CODE){
            if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
                toastMsg("成功发送支付验证码");
            } else {
                toastMsg("发送支付验证码失败");
            }
        } else if (requestAction == REQUEST_ACTION_POST_TASK_PAY){
            if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
                List<BrandItemInfoWo.DataBean.ResultBean> resultBeanList = brandItemInfoWo.getData().getResult();
                if (resultBeanList == null){
                    toastMsg("没对应的查询结果");
                } else {
                    if (resultBeanList.size() == 0){
                        toastMsg("没对应的查询结果");
                    } else {
                        SearchResultListActivity.start(CommonDistinguishActivity.this, brandItemInfoWo, TaskID);
                    }
                }
            } else {
                toastMsg("支付失败");
            }
        }

    }

    private void showPasswordTaskPayDialog(){
        if (passwordTaskPayDialog == null){
            passwordTaskPayDialog = new TaskPayDialog(CommonDistinguishActivity.this, TaskPayDialog.STATUS_PASSWORD,
                    new TaskPayDialog.OnSureClickListener(){

                        @Override
                        public void onSureClick(String value) {
                            presenter.postTaskPay(REQUEST_ACTION_POST_TASK_PAY, TaskID, MD5Uitl.getMd5Value(value));
                            passwordTaskPayDialog.dismiss();
                        }
                    });
        }
        passwordTaskPayDialog.show();
    }

    private void showValidCodeTaskPayDialog(){
        if (validCodeTaskPayDialog == null){
            validCodeTaskPayDialog = new TaskPayDialog(CommonDistinguishActivity.this, TaskPayDialog.STATUS_VALID_CODE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            presenter.postTaskPayCode(REQUEST_ACTION_POST_TASK_PAY_CODE);
                        }
                    },
                    new TaskPayDialog.OnSureClickListener() {
                        @Override
                        public void onSureClick(String value) {
                            presenter.postTaskPay(REQUEST_ACTION_POST_TASK_PAY, TaskID, value);
                            validCodeTaskPayDialog.dismiss();
                        }
                    });
        }
    }

    private void showClickImagToSelectClassDialog() {
        ToastDialog toastDialog = new ToastDialog(CommonDistinguishActivity.this, false, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ProductClassfiyActivity.startForResult(CommonDistinguishActivity.this, REQUEST_CODE_GET_CLASSFIY_CODE);
                isClickImgToSelectMarkClass = true;
                dialog.dismiss();
            }
        });
        toastDialog.setTvContent("请必须且只选一个类别");
        toastDialog.show();
    }

    private class MyCountDownTimer extends CountDownTimer{
        public MyCountDownTimer() {
            this(30000, 1000);
        }//[总计时间,时间间隔]

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            /**
             * 挂起
             */
        }

        @Override
        public void onFinish() {
            /**
             * 如果30秒无数据返回，则中断该请求，执行2.4.13（请求获取商标查询结果）
             */
            presenter.dispose(REQUEST_ACTION_POST_BRAND_DISTINGUISH);
            toastMsg("后台响应时间过长，查询时间已超过30秒，无数据返回，请用户稍后通过【我的->处理进程】中对照您的查询时间进行查看后台处理结果！谢谢合作！",1);
            presenter.postSearchResultByTaskID(REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID, TaskID, "", 1, pageSize);
        }
    }
}
